<template>
  <el-autocomplete
    ref="elInput"
    :value="value"
    :fetch-suggestions="handleFetchSuggestions"
    v-bind="$props.props"
    clearable
    v-on="$listeners"
    @select="handleSelect"
    @change="valueChange"
    @input="valueChange"
  />
</template>

<script>
import Vue from 'vue';
import {Autocomplete} from "element-ui";
Vue.use(Autocomplete);
/**
 * 自动完成输入框
 */
export default {
  name: "ErpFormAutoComplete",
  components: {
  },
  props: {
    /**
     * 标题
     * @public
     */
    title: {
      type: String,
      default: '',
    },
    /**
     * 选项，下拉意见的数据源
     * @public
     */
    options: {
      type: Array,
      default () {
        return [];
      },
    },
    /**
     * 字段名
     * @public
     */
    field: {
      type: String,
      default: ''
    },
    /**
     * 默认值
     * @public
     */
    value: {
      default () {
        return '';
      }
    },
    /**
     * element-ui的[el-autocomplete](https://element.eleme.cn/#/zh-CN/component/input#autocomplete-attributes)
     * @public
     */
    props: {
      type: Object,
      default () {
        return {
        };
      }
    },
  },
  computed: {
  },
  mounted() {
  },
  methods: {
    /**
     * 使 input 获取焦点
     * @public
     */
    focus () {
      this.$refs.elInput.focus();
    },
    /**
     * 监听值变化
     * @private
     * @param {string} e 值
     */
    valueChange (e) {
      /**
       * 通知父组件值改变了
       */
      this.$emit('value-change', e);
    },
    /**
     * 监听选择
     * @private
     * @param {object} e 选中的选项对象
     */
    handleSelect (e) {
      this.valueChange(e[this.props.valueKey]);
    },
    /**
     * 查询下拉建议
     * @private
     * @param {string} queryString 搜索的字符串
     * @param {function} cb 回调结果集
     */
    handleFetchSuggestions (queryString, cb) {
      let data = this.options;
      let results = queryString ? data.filter(this.createFilter(queryString)) : data;
      cb(results);
    },
    /**
     * 过滤选项的函数
     * @private
     * @param {string} queryString 查询的字符串
     */
    createFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
  }
};
</script>

<style lang="scss" scoped>
    .el-autocomplete{
        width: 100%;
    }
</style>
